<?php

/**
 * Created by PhpStorm.
 * User: hoter
 * Date: 2016/9/2
 * Time: 22:08
 */
namespace app\core\behaviors;

use Yii;
use yii\base\ActionFilter;

class ThemeBehavior extends ActionFilter
{

    public $themeParam = 'theme';
    public $themeCookieName = 'localThemeName';
    public function beforeAction($action)
    {
        $themeName = $this->resolveTheme();
        $this->setTheme($themeName);
        return true;
    }
    public function resolveTheme()
    {
        //先看参数
        if (!$themeName = Yii::$app->request->get($this->themeParam)) {
            //再检查cookie
            if (Yii::$app->request->cookies->has($this->themeCookieName)) {
                $themeName = Yii::$app->request->cookies->get($this->themeCookieName);
            } else {
                //最后读系统默认
                /*$isMobile = 0;
                if ($isMobile) {
                    $themeName = 'mobile';
                } else {
                    $themeName = 'basic';
                }*/
            }
        }
        return $themeName;
    }
    public function setTheme($themeName)
    {
        $theme = [
            'class' => 'yii\base\Theme',
            'basePath' => '@app/themes/' . $themeName,
            'baseUrl' => '@web/themes/' . $themeName,
            'pathMap' => [
                '@app/views' => [
                    '@app/themes/' . $themeName,
                    '@app/themes/basic',
                ],
            ],
        ];
        \Yii::$app->view->theme = \Yii::createObject($theme);
    }
}